package cn.qdu.dao;

import cn.qdu.model.Post;
import cn.qdu.model.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class PostDao {
    // 创建日志
    public boolean createPost(Post post) throws SQLException {
        // 完全匹配表结构的SQL
        String sql = "INSERT INTO posts(user_id, content, visibility, location) VALUES(?, ?, ?, ?)";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            // 严格按表结构顺序设置参数
            stmt.setString(1, post.getUserId());    // user_id (varchar30)
            stmt.setString(2, post.getContent());   // content (text)
            stmt.setString(3, post.getVisibility()); // visibility (enum)
            stmt.setString(4, post.getLocation());  // location (varchar100)

            int affectedRows = stmt.executeUpdate();

            if (affectedRows > 0 && post.getImages() != null) {
                try (ResultSet rs = stmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        savePostImages(conn, rs.getInt(1), post.getImages());
                    }
                }
            }
            return affectedRows > 0;
        }
    }

    private void savePostImages(Connection conn, int postId, List<String> images) throws SQLException {
        String sql = "INSERT INTO post_images(post_id, image_path) VALUES(?, ?)";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            for (String path : images) {
                stmt.setInt(1, postId);
                stmt.setString(2, path);
                stmt.addBatch();
            }
            stmt.executeBatch();
        }
    }

    // 更新日志
    public boolean updatePost(Post post) throws SQLException {
        String sql = "UPDATE posts SET content = ?, visibility = ?, location = ? WHERE post_id = ? AND user_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, post.getContent());
            stmt.setString(2, post.getVisibility());
            stmt.setString(3, post.getLocation());
            stmt.setInt(4, post.getPostId());
            stmt.setString(5, post.getUserId());

            return stmt.executeUpdate() > 0;
        }
    }

    // 删除日志
    public boolean deletePost(int postId, String userId) throws SQLException {
        String sql = "DELETE FROM posts WHERE post_id = ? AND user_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);
            stmt.setString(2, userId);

            return stmt.executeUpdate() > 0;
        }
    }

    // 修改后的获取日志方法，支持分页（已移除verified字段）
    public List<Post> getPostsForUser(String userId, String viewerId) throws SQLException {
        List<Post> posts = new ArrayList<>();
        String sql = "SELECT p.*, u.nickname, u.avatar FROM posts p " +
                "JOIN users u ON p.user_id = u.user_id " +
                "WHERE p.visibility = 'public' " +
                "OR p.user_id = ? " + // 用户自己的动态
                "OR (p.visibility = 'friends' AND EXISTS (" +
                "SELECT 1 FROM friendships f WHERE " +
                "(f.user_id = p.user_id AND f.friend_id = ? AND f.status = 'accepted') " +
                "OR (f.user_id = ? AND f.friend_id = p.user_id AND f.status = 'accepted'))) " +
                "ORDER BY p.created_at DESC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            stmt.setString(2, viewerId);
            stmt.setString(3, viewerId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    try {
                        Post post = extractPostFromResultSet(rs);

                        // 内容过滤
                        if (post.getContent() != null) {
                            post.setContent(post.getContent().replaceAll("[^\\x20-\\x7E]", ""));
                        }

                        posts.add(post);
                    } catch (SQLException e) {
                        System.err.println("记录映射失败，post_id=" + rs.getInt("post_id"));
                        e.printStackTrace();
                    }
                }
            }
        }
        return posts;
    }

    private List<String> getPostImages(int postId) throws SQLException {
        List<String> images = new ArrayList<>();
        String sql = "SELECT image_path FROM post_images WHERE post_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, postId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    String imagePath = rs.getString("image_path");
                    if(imagePath != null) {
                        images.add(imagePath);
                    }
                }
            }
        }
        return images;
    }

    // 新增方法：获取总日志数
    public int getTotalPostsCount(String userId, String viewerId) throws SQLException {
        String sql = "SELECT COUNT(*) FROM posts p " +
                "WHERE (p.visibility = 'public' OR " +
                "(p.visibility = 'friends' AND EXISTS " +
                "(SELECT 1 FROM friendships f WHERE " +
                "(f.user_id = p.user_id AND f.friend_id = ? AND f.status = 'accepted') OR " +
                "(f.user_id = ? AND f.friend_id = p.user_id AND f.status = 'accepted'))) OR " +
                "p.user_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, viewerId);
            stmt.setString(2, viewerId);
            stmt.setString(3, viewerId);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt(1);
                }
            }
        }
        return 0;
    }

    // 根据ID获取日志
    public Post getPostById(int postId, String viewerId) throws SQLException {
        String sql = "SELECT p.*, u.nickname, u.avatar FROM posts p " +
                "JOIN users u ON p.user_id = u.user_id " +
                "WHERE p.post_id = ? AND " +
                "(p.visibility = 'public' OR " +
                "(p.visibility = 'friends' AND EXISTS " +
                "(SELECT 1 FROM friendships f WHERE " +
                "(f.user_id = p.user_id AND f.friend_id = ? AND f.status = 'accepted') OR " +
                "(f.user_id = ? AND f.friend_id = p.user_id AND f.status = 'accepted'))) OR " +
                "p.user_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);
            stmt.setString(2, viewerId);
            stmt.setString(3, viewerId);
            stmt.setString(4, viewerId);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    Post post = new Post();
                    post.setPostId(rs.getInt("post_id"));
                    post.setUserId(rs.getString("user_id"));
                    post.setContent(rs.getString("content"));
                    post.setVisibility(rs.getString("visibility"));
                    post.setLocation(rs.getString("location"));
                    post.setCreatedAt(rs.getTimestamp("created_at"));

                    User user = new User();
                    user.setUserId(rs.getString("user_id"));
                    user.setNickname(rs.getString("nickname"));
                    user.setAvatar(rs.getString("avatar"));
                    post.setUser(user);

                    // 关键修改：加载图片
                    List<String> images = getPostImages(postId);
                    post.setImages(images);

                    return post;
                }
            }
        }
        return null;
    }


    // 获取用户最近的日志
    public List<Post> getRecentPosts(String userId, int limit) throws SQLException {
        List<Post> posts = new ArrayList<>();
        String sql = "SELECT p.*, u.nickname, u.avatar FROM posts p " +
                "JOIN users u ON p.user_id = u.user_id " +
                "WHERE p.user_id = ? " +
                "ORDER BY p.created_at DESC LIMIT ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            stmt.setInt(2, limit);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Post post = new Post();
                    post.setPostId(rs.getInt("post_id"));
                    post.setUserId(rs.getString("user_id"));
                    post.setContent(rs.getString("content"));
                    post.setVisibility(rs.getString("visibility"));
                    post.setLocation(rs.getString("location"));
                    post.setCreatedAt(rs.getTimestamp("created_at"));

                    User user = new User();
                    user.setUserId(rs.getString("user_id"));
                    user.setNickname(rs.getString("nickname"));
                    user.setAvatar(rs.getString("avatar"));
                    post.setUser(user);

                    posts.add(post);
                }
            }
        }
        return posts;
    }

    // 在PostDao类中添加以下方法
    public List<Post> getPublicPosts(String userId) throws SQLException {
        List<Post> posts = new ArrayList<>();
        String sql = "SELECT p.*, u.nickname, u.avatar FROM posts p " +
                "JOIN users u ON p.user_id = u.user_id " +
                "WHERE p.visibility = 'public' AND p.user_id != ? " +
                "ORDER BY p.created_at DESC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    posts.add(extractPostFromResultSet(rs));
                }
            }
        }
        return posts;
    }

    public List<Post> getFriendsPosts(String userId) throws SQLException {
        List<Post> posts = new ArrayList<>();
        String sql = "SELECT p.*, u.nickname, u.avatar FROM posts p " +
                "JOIN users u ON p.user_id = u.user_id " +
                "WHERE p.visibility = 'friends' AND " +
                "EXISTS (SELECT 1 FROM friendships f WHERE " +
                "(f.user_id = p.user_id AND f.friend_id = ? AND f.status = 'accepted') OR " +
                "(f.user_id = ? AND f.friend_id = p.user_id AND f.status = 'accepted')) " +
                "ORDER BY p.created_at DESC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            stmt.setString(2, userId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    posts.add(extractPostFromResultSet(rs));
                }
            }
        }
        return posts;
    }

    public List<Post> getUserPosts(String userId) throws SQLException {
        List<Post> posts = new ArrayList<>();
        String sql = "SELECT p.*, u.nickname, u.avatar FROM posts p " +
                "JOIN users u ON p.user_id = u.user_id " +
                "WHERE p.user_id = ? " +
                "ORDER BY p.created_at DESC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    posts.add(extractPostFromResultSet(rs));
                }
            }
        }
        return posts;
    }

    public void incrementCommentCount(int postId) throws SQLException {
        String sql = "UPDATE posts SET comment_count = comment_count + 1 WHERE post_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);
            stmt.executeUpdate();
        }
    }
    public int getCommentCount(int postId) throws SQLException {
        String sql = "SELECT comment_count FROM posts WHERE post_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt("comment_count");
                }
                return 0;
            }
        }
    }

    // 辅助方法：从ResultSet提取Post对象
    private Post extractPostFromResultSet(ResultSet rs) throws SQLException {
        Post post = new Post();
        post.setPostId(rs.getInt("post_id"));
        post.setUserId(rs.getString("user_id"));
        post.setContent(rs.getString("content"));
        post.setVisibility(rs.getString("visibility"));
        post.setLocation(rs.getString("location"));
        post.setCreatedAt(rs.getTimestamp("created_at"));

        // 用户信息
        User user = new User();
        user.setUserId(rs.getString("user_id"));
        user.setNickname(rs.getString("nickname"));
        user.setAvatar(rs.getString("avatar"));
        post.setUser(user);

        // 关键修改：加载图片
        int postId = rs.getInt("post_id");
        List<String> images = getPostImages(postId);
        post.setImages(images);

        return post;
    }
}